package logic

import (
	"context"
	"github.com/pkg/errors"
	"user_srv/model/mysql"
	"user_srv/pkg"

	"user_srv/internal/svc"
	"user_srv/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type RealNameLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewRealNameLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RealNameLogic {
	return &RealNameLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *RealNameLogic) RealName(in *user.RealNameRequest) (*user.RealNameResponse, error) {
	// todo: add your logic here and delete this line
	var u mysql.RealName_user
	err := u.GetUser(in.UserId, in.IdCard)
	if err != nil {
		logx.Error("实名失败")
		return nil, errors.New("实名认证失败")
	}
	if u.ID > 0 {
		logx.Error("实名失败")
		return nil, errors.New("该用户已被实名")
	}
	if !pkg.RealName(in.IdCard, in.RealName) {
		logx.Error("实名失败")
		return nil, errors.New("实名认证失败")
	}
	u.UserId = in.UserId
	u.RealName = in.RealName
	u.IdCard = in.IdCard
	err = u.Create()
	if err != nil {
		logx.Error("实名失败")
		return nil, errors.New("实名认证失败")
	}
	return &user.RealNameResponse{Id: int64(u.ID)}, nil
}
